<?php

namespace Frieza\Modules\Tag\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\Tag\NewTag;
use Doraemon\model\Tag\NewTagRelation;
use Doraemon\model\Tag\NewTagType;
use Doraemon\service\Tag\TagList;
use Doraemon\service\Tag\TagRelation as sTagRelation;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Box;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Doraemon\cache\Queue;

class TagController extends Controller
{

    const PAGE_SIZE = 20;

    public function list(Request $request, Content $content)
    {
        $params = [
            'tag'      => $request->input('tag', ''),
            'page'     => $request->input('page', 1),
            'per_page' => $request->input('per_page', 20)
        ];
        return $content
            ->header('标签列表')
            ->breadcrumb(
                [
                    'text' => '标签列表',
                    'url'  => '/tag/list'
                ]
            )
            ->body(self::listAction($params));
    }

    private static function listAction($params = [])
    {
        $data = TagList::getList($params);
        $gridModel = new pGridDataModel($data['data'], $data['total'], [
            'perPage' => $params['per_page'],
        ]);
        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->paginate(20);
            $grid->fixColumns(4, -2);
            // 筛选项
            $grid->filter(function (Grid\Filter $filter) {
                $filter->disableIdFilter();
                $filter->column(1 / 2, function ($filter) {
                    $filter->equal('tag', '标签名称')->placeholder('请输入标签名称');
                });
            });
            $grid->column('id');
            $grid->column('tagtype', '所属类')->display(function ($tagtype) {
                return NewTagType::getTreeById($tagtype);
            });
            $grid->column('tag', '标签名');
            $grid->column('tag_alias', '别名')->display(function () {
                return self::stringToArr($this->tag_alias);
            })->label('default');
            $grid->column('mapped', '关联的标签')->display(function () {
                return self::stringToArr($this->mapped);
            })->label('default');

            $grid->column('tagRelation', '各场景是否生效')->display(function () {
                return self::RTshow($this->tagRelation ?? []);
            });
        });

        return $listGrid;
    }

    public function edit($id = 0, Content $content)
    {
        $tab = new Tab();
        if ($id > 0) {
            $title = '标签编辑';
        } else {
            $title = '创建标签';
        }
        $tab->add("$title", $this->editAction($id));
        return $content
            ->header('标签管理')
            ->breadcrumb(
                [
                    'text' => '标签列表',
                    'url'  => '/tag/list'
                ],
                ['text' => "$title"]
            )
            ->body($tab);
    }

    private function editAction($id = 0)
    {

        if ($id > 0) {
            $info = TagList::getInfoById($id);
            // 获取一级分类id
            $ptypeId = NewTagType::getPtypeById($info['tagtype']);
            if (!empty($ptypeId[0])) {
                $info['ptagtype'] = $ptypeId[0]['parent_id'];
            }
            // 获取已有的关联标签，重组成规定格式
            $mapped = explode(',', $info['mapped']);
            $info['mapped'] = array_combine($mapped, $mapped);
            $tagrelationData = sTagRelation::getInfoByTagid($id);
            // 组装全部的数据
            $allinfo = TagList::getAllInfo($info, $tagrelationData);
            $form = new Form($allinfo);
            $form->hidden('id');
            $form->text('tag', '标签名')->readonly();
        } else {
            $form = new Form();
            $form->text('tag', '标签名')->required('不能为空');
        }
        $form->tags('tag_alias', '别名');

        $form->select('ptagtype', '一级分类')->options('/admin/tag/list/edit/tagtype')
            ->load('tagtype', '/admin/tag/list/edit/tagtype')
            ->required('不能为空');

        $form->select('tagtype', '二级分类')->required('不能为空');
        $form->multipleSelect('mapped', '关联标签')
            ->options($allinfo['mapped'] ?? [])
            ->ajax('/admin/tag/list/edit/tag/relation')
            ->help('输入关键词搜索');
        // 用来编写规则
        foreach (NewTagRelation::RELATION_TYPE as $key => $value) {
            $form->fieldset(NewTagRelation::RELATION_TYPE[$key], function (Form $form) use ($key) {
                $form->hidden("relation_type.$key")
                    ->options(NewTagRelation::RELATION_TYPE)
                    ->default($key);
                $form->fieldChange("rule_type.$key", "规则类型", $form)
                    ->default(NewTagRelation::RELATION_TYPE_VALID_DEFAULE_VALUE[$key])
                    ->options(NewTagRelation::RULE_TYPE)
                    ->required()
                    ->callableMap([
                        NewTagRelation::RELATION_RULE_TYPE_NEVER_NO_EXPIRES => function (Form $form) {
                        },
                        NewTagRelation::RELATION_RULE_TYPE_NEVER_EXPIRES    => function (Form $form) {
                        },
                        NewTagRelation::RELATION_RULE_TYPE_EXPIRES_TIME     => function (Form $form) use ($key) {
                            $form->radio("expires_repeat_type." . $key, "是否重复指定时间")
                                ->options(NewTagRelation::REPEAT_TYPE)
                                ->default(NewTagRelation::REPEAT_TYPE_ON)
                                ->help("每年重复的数据请不要跨年，跨年请转化成不跨年的另一种指定时间规则类型，每年11月至第二年1月无效的标签等效于每年1月到11月有效的标签");
                            $form->dateRange("starttime.$key", "endtime.$key", "选择时间");
                        },
                        NewTagRelation::RELATION_RULE_TYPE_NO_EXPIRES_TIME  => function (Form $form) use ($key) {
                            $form->radio("no_expires_repeat_type." . $key, "是否重复指定时间")
                                ->options(NewTagRelation::REPEAT_TYPE)
                                ->default(NewTagRelation::REPEAT_TYPE_ON)
                                ->help("每年重复的数据请不要跨年，跨年请转化成不跨年的另一种指定时间规则类型，每年11月至第二年1月无效的标签等效于每年1月到11月有效的标签");
                            $form->dateRange("starttime.$key", "endtime.$key", '选择时间');
                        }
                    ]);
            });
        }
        $form->action('/admin/tag/list/save');

        return $form;
    }

    /**
     * 保存
     *
     * @param Request $request
     */
    public function saveSubmit(Request $request)
    {
        $params = $request->all();
        // 判断标签名是否重复
        $res = TagList::getInfoByTag($params['tag'], 'id');
        if ($res != NULL) {
            if (isset($params['id'])) {
                if ($params['id'] != $res) {
                    $error = new MessageBag([
                        'title' => '标签名重复',
                    ]);
                    return back()->with(compact('error'));
                }
            } else {
                $error = new MessageBag([
                    'title' => '标签名重复',
                ]);
                return back()->with(compact('error'));
            }
        }

        try {
            TagList::save($params);
            return back()->with('success', new MessageBag([
                'title' => '操作成功'
            ]));
        } catch (\Exception $e) {
            return back()->with('error', new MessageBag([
                'title' => $e->getMessage()
            ]));
        }
    }

    /**
     * 获取分类
     *
     * @param Request $request
     * @return void
     */
    public function getTagType(Request $request)
    {
        $pid = $request->input('q', 0);

        $result = NewTagType::getInfoByPid($pid);

        $categories = array_map(function ($category) {
            return [
                "id"   => $category["id"],
                "text" => $category["name"]
            ];
        }, $result);

        return response()->json($categories);
    }

    /**
     * 异步加载全部标签
     *
     * @param Request $request
     * @return void
     */
    public function getTagRelation(Request $request)
    {
        $tag = $request->input('q', ' ');

        $result = TagList::getTagByName($tag);
        $tags = [
            "total"         => 4,
            "per_page"      => 15,
            "current_page"  => 1,
            "last_page"     => 1,
            "next_page_url" => null,
            "prev_page_url" => null,
            "from"          => 1,
            "to"            => 3,
        ];
        $tags['data'] = array_map(function ($res) {
            return [
                'id'   => $res['tag'],
                'text' => $res['tag'],
            ];
        }, $result);

        return response()->json($tags);
    }

    /**
     * 删除
     *
     *
     * @param $id
     * @return void
     */
    public function del($id)
    {
        $tag_info = NewTag::getOneByWhere(['id'=>$id]);
        NewTag::delTagById($id);
        if($tag_info && is_array($tag_info)) {
            Queue::insertQueue('queue/Search/AddLexiconWord', array(
                'word' => $tag_info['tag'],
                'type' => "delete",
                'origin_word' => ""
            ), Queue::QUEUE_DORAEMON);
        }

        return response()->json([
            'status'  => true,
            'message' => "操作成功",
        ]);
    }

    private static function stringToArr($str = '')
    {
        $format = [];
        if ($str) {
            if (strpos($str, ',')) {
                $tagAliasArr = explode(',', $str);
                foreach ($tagAliasArr as $key => $value) {
                    $format[$value] = $value;
                }
            } else {
                $format[$str] = $str;
            }
        }
        return $format;
    }

    private static function RTshow($relations)
    {
        $relations = array_column($relations, null, 'relation_type');
        $str = '<dl class="dl-horizontal">';
        foreach (NewTagRelation::RELATION_TYPE as $relationType => $relationTypeName) {
            $dd = NewTagRelation::RULE_TYPE[$relations[$relationType]['rule_type']] ?? NewTagRelation::RULE_TYPE[NewTagRelation::RELATION_TYPE_VALID_DEFAULE_VALUE[$relationType]];
            if (in_array($relations[$relationType]['rule_type'], [
                NewTagRelation::RELATION_RULE_TYPE_EXPIRES_TIME,
                NewTagRelation::RELATION_RULE_TYPE_NO_EXPIRES_TIME
            ])) {
                $dd .= "/" . NewTagRelation::REPEAT_TYPE[$relations[$relationType]['repeat_type']] . "<br/>";
                $dd .= date('Y-m-d', strtotime($relations[$relationType]['starttime_year'] . $relations[$relationType]['starttime_day'])) . '至'
                    . date('Y-m-d', strtotime($relations[$relationType]['endtime_year'] . $relations[$relationType]['endtime_day']));
            }
            $str .= "<dt>{$relationTypeName}</dt><dd>{$dd}</dd>";
        }
        $str .= '</dl>';
        return $str;
    }

    public function show(Content $content)
    {
        $tab = new Tab();
        foreach (NewTagRelation::RELATION_TYPE as $relationType => $relationTypeName) {
            $validtags = TagList::getIncludeTagsByRelationType($relationType);
            $validTagsBox = new Box('当前有效的标签', implode(' ', array_map(function ($tag) {
                return '<span class="label label-info" style="display: inline-block">' . $tag . '</span>';
            }, $validtags)));
            $invalidtags = TagList::getExcludeTagsByRelationType($relationType);
            $invalidTagsBox = new Box('当前无效的标签', implode(' ', array_map(function ($tag) {
                return '<span class="label label-info">' . $tag . '</span>';
            }, $invalidtags)));
            $tab->add($relationTypeName . '-' . (NewTagRelation::RELATION_TYPE_VALID_DEFAULE_VALUE[$relationType] ? "默认有效" : "默认无效"), $validTagsBox . $invalidTagsBox);
        }
        return $content->body($tab);
    }
}
